from tools_algorithm import *


class Solution:
    def minOperationsToMakeMedianK(self, nums: List[int], k: int) -> int:
        nums.sort()
        n = len(nums)

        def f(mid):
            ans = abs(nums[mid] - k)
            for i in range(mid + 1, n):
                if nums[i] < k:
                    ans += k - nums[i]
            for i in range(mid - 1, -1, -1):
                if nums[i] > k:
                    ans += nums[i] - k
            return ans

        return f(n // 2) if n & 1 == 1 else f(n // 2)


s = Solution()
print(s.minOperationsToMakeMedianK(nums=[45, 50, 89, 30, 4, 5, 91, 58], k=31))
# print(s.minOperationsToMakeMedianK(nums=[2, 5, 6, 8, 5], k=7))
